var inquirer = require('inquirer')
const { Client } = require('ssh2');
// 打包文件
var archiver = require('archiver');
var fs = require('fs');
fs.readFile('.env', 'utf8', (err, data) => {
    if (err) throw err;
    const datas = data.split('\r\n')
    let info = {}
    for (const item of datas) {
        const entries = item.split('=');
        info[entries[0]] = entries[1]
    }
    console.log(info);
})
async function run() {
    try {
        const answers = await inquirer.prompt([
            {
                type: 'input',
                name: 'projectName',
                message: '需要部署的文件',
                default: 'dist',
            },
            {
                type: 'list',
                name: 'type',
                message: '压缩的格式',
                default: 'zip',
                choices: [
                    { name: 'zip', value: 'zip' },
                    { name: 'tar', value: 'tar' },
                    { name: 'rar', value: 'rar' },
                ]
            }
        ])
        console.log('当前需要部署的文件是：', answers.projectName)
        return answers
    } catch (error) {
        console.log(`错误: ${error}`)
    }
}

let answers = null;

run().then((e) => {
    answers = e;
    if (answers.projectName) {
        console.log("正在打包....")
        zip(answers.projectName);
        upload(server, "./" + answers.projectName + ".zip", '/root/mywork/' + answers.projectName + ".zip", (res) => {
            if (res) console.log(res);
        })
    }
})


/**
 * 打包文件
 * @param {*} fileName 需要打包的文件夹名
 */
function zip(fileName) {
    var zipPath = `${fileName}.zip`;
    //创建一最终打包文件的输出流
    var output = fs.createWriteStream(zipPath);
    //生成archiver对象，打包类型为zip
    var zipArchiver = archiver('zip');
    //将打包对象与输出流关联
    zipArchiver.pipe(output);
    //添加需要打包的文件夹
    zipArchiver.directory(fileName + '/', false);
    // for (var i = 0; i < files.length; i++) {
    //     console.log(files[i]);
    //     //将被打包文件的流添加进archiver对象中
    //     zipArchiver.append(fs.createReadStream(files[i]), { 'name': files[i] });
    // }
    //打包
    zipArchiver.finalize();
    console.log(zipPath + "打包成功~");
}

/**
 * 连接服务器
 * @param {*} server 
 * @param {*} callback 
 */

function connect(server, callback) {
    var conn = new Client();
    conn.on("ready", () => {
        callback(conn);
    }).on('error', (err) => {
        console.log("connect error!");
    }).on('end', () => {
        console.log("connect end!");
    }).on('close', (had_error) => {
        console.log("connect close");
    }).connect(server);
}

/**
 * 上传压缩包，并解压
 * @param {*} server 服务器信息
 * @param {*} localPath 本地文件
 * @param {*} remotePath 服务器路径
 * @param {*} callback 回调
 */
function upload(server, localPath, remotePath, callback) {
    connect(server, (conn) => {
        conn.sftp(function (err, sftp) {
            if (err) throw err;
            sftp.fastPut(localPath, remotePath, (err) => {
                if (err) {
                    callback(false)
                    throw err
                }
                console.log("上传成功")
                callback(true);
                conn.end()
            });
        });

        const newFile = "touch test.txt \necho 'hello' >>./test.txt \ncat test.txt"
        // ls \ncd mywork \nls \nsh test.sh
        conn.exec("ls \ncd mywork \nls \nsh test.sh", (err, stream) => {
            if (err) throw err;
            stream.on('close', (code, signal) => {
                console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
                conn.end();
            }).on('data', (data) => {
                console.log('STDOUT: ' + data);
            }).stderr.on('data', (data) => {
                console.log('STDERR: ' + data);
            });
        });
    })
}

/**
 * 服务器信息
 */

const server = {
    host: '49.234.54.97',
    port: 22,
    username: 'root',
    //   privateKey: readFileSync('/path/to/my/key')
    password: "Lzx0203."
}

/* upload(server, "./test.zip", '/root/opt/test.zip', (res) => {
    if (res) console.log(res);
}) */

